package com.xiangming.demo.service.imp;

import com.xiangming.demo.entity.FileData;
import com.xiangming.demo.mapper.UploadMapper;
import com.xiangming.demo.service.UploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wxm
 * @data 2021/11/13
 */
@Service
public class UploadServiceImpl implements UploadService {
    /**
     *     获取日志
     */

   private final Logger logger = LoggerFactory.getLogger(UploadServiceImpl.class);

    @Resource
    UploadMapper uploadMapper;



    /**
     * 文件上传接口
     * @param file 文件
     * @return 返回执行结果
     */
    @Override
    public Boolean uploading(MultipartFile file,String uuid) {

        //文件大小
        long size = file.getSize();
        //原始文件名
        String fileName = file.getOriginalFilename();
        //文件扩展名
        String ext = fileName.substring(fileName.lastIndexOf("."));
        //生成时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        //创建时间
        String format = simpleDateFormat.format(new Date());
        //生成底层配置

        String filePath = "C:/img/";
        File realPath = new File(filePath + format);
        if (!realPath.exists()){
            realPath.mkdirs();
        }
        logger.info("-----info------文件目录创建成功");
        //生成最终目录 文件保存目录
        String path = realPath.getPath();
        File dest = new File(path + "/" + uuid + ext);

        try {
            file.transferTo(dest);
            logger.info("-----info------ 文件已上传成功");
            FileData file1 = new FileData(fileName,ext,size,format,path,uuid);
            uploadMapper.insertAll(file1);
            logger.info("-----info------ 文件元数据已保存成功");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("-----info------ 文件已上传失败");
        return false;
    }
    }
